<template>
  <div class="login-page">
    <div class="welcome-text">
      <h1 class="welcome-title">欢迎登录种花吧</h1>
      <p class="slogan">让每一朵花都绽放生命的色彩</p>
    </div>
    <div class="login-container">
      <h2>欢迎登录</h2>

      <!-- 登录方式选择 -->
      <div class="login-mode-switcher">
        <button @click="toggleMode('password')" :class="{ active: mode === 'password' }">密码登录</button>
        <button @click="toggleMode('email')" :class="{ active: mode === 'email' }">邮箱验证码</button>
      </div>

      <!-- 密码登录表单 -->
      <form v-if="mode === 'password'" @submit.prevent="handlePasswordLogin" class="login-form">
        <div class="form-group">
          <i class="el-icon-user"></i>
          <input id="username" v-model="credentials.username" type="text" placeholder="请输入用户名" required />
        </div>
        <div class="form-group">
          <i class="el-icon-lock"></i>
          <input id="password" v-model="credentials.password" type="password" placeholder="请输入密码" required />
        </div>
        <div class="form-group">
          <div class="slider-container">
            <div class="slider-track" ref="sliderTrack">
              <div class="slider-button" 
                   :style="{ left: sliderValue + '%' }"
                   @mousedown="startDrag"
                   @touchstart="startDrag"
                   :class="{ 'verified': isVerified }">
                <i class="el-icon-d-arrow-right"></i>
              </div>
              <div class="slider-progress" :style="{ width: sliderValue + '%' }"></div>
              <span class="slider-text">{{ isVerified ? '验证通过' : '向右滑动验证' }}</span>
            </div>
          </div>
        </div>
        <div class="form-group">
          <button type="submit" class="submit-btn" :disabled="!isVerified">登 录</button>
        </div>
      </form>

      <!-- 邮箱验证码登录表单 -->
      <form v-else @submit.prevent="handleEmailLogin" class="login-form">
        <div class="form-group">
          <i class="el-icon-message"></i>
          <input id="email" v-model="credentials.email" type="email" placeholder="请输入邮箱" required />
          <button @click="sendVerificationCode" type="button" class="code-btn">获取验证码</button>
        </div>
        <div class="form-group">
          <i class="el-icon-key"></i>
          <input id="verificationCode" v-model="credentials.verificationCode" type="text" placeholder="请输入验证码" required />
        </div>
        <div class="form-group">
          <button type="submit" class="submit-btn">登 录</button>
        </div>
      </form>
      
      <div class="additional-links">
        <router-link to="/saveuser" class="register-link">免费注册</router-link>
        <a href="#" class="forgot-password">忘记密码？</a>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mode: 'password',
      credentials: {
        username: '',
        password: '',
        email: '',
        verificationCode: ''
      },
      sliderValue: 0,
      isVerified: false,
      isDragging: false,
      startX: 0,
      sliderLeft: 0
    };
  },
  methods: {
    toggleMode(mode) {
      this.mode = mode;
      this.credentials = {
        username: '',
        password: '',
        email: '',
        verificationCode: ''
      };
    },
    handlePasswordLogin() {
      const loginData = {
        username: this.credentials.username,
        password: this.credentials.password
      };

      // 发送登录请求并等待响应
      this.request.post("/users/login", loginData)
        .then(res => {
          console.log('登录响应:', res);
          if (res.code === '1' || res.code === 1) {
            // 保存token
            localStorage.setItem('token', res.data.token);
            // 保存用户信息
            sessionStorage.setItem('user', JSON.stringify(res.data));
            this.request.defaults.headers.common['token'] = res.data.token;          
            // 显示成功消息
            this.$message.success('登录成功');
            // 跳转到首页
            this.$router.push('/home');
          } else {
            this.$message.error(res.msg || '登录失败');
          }
        })
        .catch(error => {
          console.error('登录错误:', error);
          // 显示具体错误信息
          if (error.response) {
            console.log('错误响应:', error.response);
            this.$message.error(error.response.data.msg || '登录失败，请检查网络连接');
          } else {
            this.$message.error('登录失败，请稍后重试');
          }
        });
    },
    handleEmailLogin() {
      const loginData = {
        email: this.credentials.email,
        code: this.credentials.verificationCode
      };

      // 发送邮箱登录请求并等待响应
      this.request.post("/users/login/email", loginData)
        .then(res => {
          console.log('邮箱登录响应:', res);
          if (res.code === '1' || res.code === 1) {
            // 保存token
            localStorage.setItem('token', res.data.token);
            // 保存用户信息
            sessionStorage.setItem('user', JSON.stringify(res.data));
            // 显示成功消息
            this.$message.success('登录成功');
            // 跳转到首页
            this.$router.push('/home');
          } else {
            this.$message.error(res.msg || '登录失败');
          }
        })
        .catch(error => {
          console.error('登录错误:', error);
          if (error.response) {
            console.log('错误响应:', error.response);
            this.$message.error(error.response.data.msg || '登录失败，请检查网络连接');
          } else {
            this.$message.error('登录失败，请稍后重试');
          }
        });
    },
    sendVerificationCode() {
      if (!this.credentials.email) {
        this.$message.warning('请输入邮箱地址');
        return;
      }
      
      // 直接提示发送成功
      this.$message.success('验证码已发送（测试模式）');
      
      // 可选：仍然发送请求，但不等待响应
      this.request.post("/users/email/code", { email: this.credentials.email })
        .then(res => {
          console.log('验证码发送响应:', res);
        })
        .catch(error => {
          console.error('发送验证码错误:', error);
        });
    },
    startDrag(e) {
      if (this.isVerified) return;
      
      this.isDragging = true;
      this.startX = e.type === 'mousedown' ? e.clientX : e.touches[0].clientX;
      this.sliderLeft = this.sliderValue;

      if (e.type === 'mousedown') {
        document.addEventListener('mousemove', this.onDrag);
        document.addEventListener('mouseup', this.stopDrag);
      } else {
        document.addEventListener('touchmove', this.onDrag);
        document.addEventListener('touchend', this.stopDrag);
      }
    },
    onDrag(e) {
      if (!this.isDragging) return;

      const currentX = e.type === 'mousemove' ? e.clientX : e.touches[0].clientX;
      const deltaX = currentX - this.startX;
      const trackWidth = this.$refs.sliderTrack.offsetWidth;
      const buttonWidth = 40; // 滑块宽度

      let newValue = this.sliderLeft + (deltaX / (trackWidth - buttonWidth)) * 100;
      newValue = Math.max(0, Math.min(100, newValue));
      
      this.sliderValue = newValue;
      
      if (newValue >= 95) {
        this.isVerified = true;
        this.stopDrag();
        this.$message.success('验证通过');
      }
    },
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
      document.removeEventListener('touchmove', this.onDrag);
      document.removeEventListener('touchend', this.stopDrag);
      
      if (!this.isVerified) {
        this.sliderValue = 0;
      }
    }
  },
  beforeDestroy() {
    document.removeEventListener('mousemove', this.onDrag);
    document.removeEventListener('mouseup', this.stopDrag);
    document.removeEventListener('touchmove', this.onDrag);
    document.removeEventListener('touchend', this.stopDrag);
  }
};
</script>

<style scoped>
.login-page {
  background: linear-gradient(135deg, #e6f3ff 0%, #ffffff 100%);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10%;
  position: relative;
}

.welcome-text {
  color: #2c3e50;
  max-width: 500px;
  animation: fadeIn 1s ease-out;
}

.welcome-title {
  font-size: 3.5em;
  font-weight: 600;
  margin-bottom: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
  background: linear-gradient(45deg, #3498db, #2980b9);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: titleGlow 2s infinite alternate;
}

.slogan {
  font-size: 1.5em;
  line-height: 1.6;
  color: #3498db;
  font-style: italic;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateX(-50px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes titleGlow {
  from {
    text-shadow: 0 0 10px rgba(52, 152, 219, 0.3);
  }
  to {
    text-shadow: 0 0 20px rgba(52, 152, 219, 0.5);
  }
}

.login-container {
  width: 400px;
  padding: 30px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(52, 152, 219, 0.1);
  backdrop-filter: blur(10px);
  animation: slideIn 0.5s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 500;
}

.login-mode-switcher {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  gap: 20px;
}

.login-mode-switcher button {
  padding: 10px 20px;
  border: none;
  background: transparent;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.login-mode-switcher button.active {
  color: #3498db;
}

.login-mode-switcher button.active::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #3498db;
  animation: slideWidth 0.3s ease-out;
}

@keyframes slideWidth {
  from { width: 0; }
  to { width: 100%; }
}

.login-form {
  margin-top: 20px;
}

.form-group {
  position: relative;
  margin-bottom: 20px;
}

.form-group i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
}

input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
  outline: none;
}

.code-btn {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  padding: 8px 15px;
  border: none;
  background: #3498db;
  color: white;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.code-btn:hover {
  background: #2980b9;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.submit-btn:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.additional-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding: 0 10px;
}

.register-link, .forgot-password {
  color: #666;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s ease;
}

.register-link:hover, .forgot-password:hover {
  color: #3498db;
}

@media (max-width: 768px) {
  .login-page {
    padding: 20px;
    flex-direction: column;
    justify-content: center;
  }

  .welcome-text {
    text-align: center;
    margin-bottom: 30px;
  }

  .welcome-title {
    font-size: 2.5em;
  }

  .slogan {
    font-size: 1.2em;
  }

  .login-container {
    width: 100%;
    max-width: 400px;
  }
}

/* 滑动验证器样式 */
.slider-container {
  width: 100%;
  padding: 10px 0;
}

.slider-track {
  position: relative;
  width: 100%;
  height: 40px;
  background-color: #f5f5f5;
  border-radius: 20px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
  touch-action: none;
}

.slider-button {
  position: absolute;
  top: 50%;
  left: 0;
  width: 40px;
  height: 40px;
  background: #fff;
  border-radius: 50%;
  transform: translateY(-50%);
  cursor: grab;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  transition: background-color 0.3s;
  border: 1px solid #e4e7ed;
}

.slider-button:active {
  cursor: grabbing;
}

.slider-button i {
  color: #909399;
  font-size: 20px;
  transition: all 0.3s;
}

.slider-button.verified {
  background-color: #67C23A;
  border-color: #67C23A;
}

.slider-button.verified i {
  color: white;
  transform: scale(1.2);
}

.slider-progress {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background-color: #e1f3ff;
  transition: width 0.1s;
  border-right: 1px solid #e4e7ed;
}

.slider-text {
  position: absolute;
  width: 100%;
  text-align: center;
  line-height: 40px;
  color: #909399;
  font-size: 14px;
  user-select: none;
  z-index: 1;
}

/* 修改登录按钮禁用状态样式 */
.submit-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.submit-btn:disabled:hover {
  background: #c0c4cc;
  transform: none;
  box-shadow: none;
}
</style>